<script setup lang="tsx">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import { PlusSearch, type PlusColumn } from "plus-pro-components";
import { ElMessage } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import dialogForms, { type FormProps } from "./handle.vue";
import { handleCharge, getChargeList } from "@/api/user";
import { utils, writeFile } from "xlsx";
import { formatDate } from "@/utils/common";
defineOptions({
  name: "UserCharge"
});
import { useMenu } from "@/utils/power";
const power = useMenu(["exportExcel", "handle"]);

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "金额搜索",
    width: 200,
    labelWidth: 100,
    prop: "amount",
    valueType: "input-number",
    fieldProps: {
      controls: true,
      step: 100
    },
    tooltip: "搜索大于等于当前输入金额"
  },
  {
    label: "充值方式",
    labelWidth: 100,
    width: 200,
    prop: "posType",
    valueType: "select",
    options: [
      {
        label: "收钱吧",
        value: 1
      },
      {
        label: "拉卡拉",
        value: 2
      },
      {
        label: "对公账户",
        value: 3
      },
      {
        label: "现金",
        value: 4
      },
      {
        label: "其他",
        value: 5
      }
    ]
  },
  {
    label: "部门",
    labelWidth: 60,
    width: 200,
    prop: "section",
    valueType: "select",
    options: [
      {
        label: "一部",
        value: 1
      },
      {
        label: "二部",
        value: 2
      },
      {
        label: "三部",
        value: 3
      },
      {
        label: "五部",
        value: 4
      },
      {
        label: "六部",
        value: 5
      },
      {
        label: "八部",
        value: 6
      },
      {
        label: "九部",
        value: 7
      },
      {
        label: "营销中心",
        value: 8
      },
      {
        label: "未知",
        value: 9
      }
    ]
  },
  {
    label: "选择时间范围",
    labelWidth: 120,
    width: 600,
    prop: "dateRange",
    valueType: "date-picker",
    tooltip: "请选择时间段",
    fieldProps: {
      type: "daterange",
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "处理时间",
    labelWidth: 120,
    width: 600,
    prop: "handleTime",
    valueType: "date-picker",
    tooltip: "请选择时间",
    fieldProps: {
      type: "date",
      placeholder: "处理时间",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "待处理",
        value: "0",
        color: "red"
      },
      {
        label: "成功",
        value: "1",
        color: "blue"
      },
      {
        label: "驳回",
        value: "2",
        color: "green"
      }
    ]
  }
];
const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if ((target.prop == "keyWord", target.prop == "amount")) {
    return;
  }
  onKeywordChange(value);
};

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  params,
  loadData,
  onKeywordChange,
  onCurrentChange
} = useColumns();
const columnsRef = computed(() => {
  if (power.value.handle) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

function doClick(row) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  addDialog({
    title: "处理充值",
    width: "30%",
    draggable: true,
    sureBtnLoading: true,
    contentRenderer: () => dialogForms,
    props: {
      formInline: {
        rechargeId: row.rId,
        status: row.status,
        notes: row.notes
      }
    },
    beforeSure: (done, { options, index }) => {
      const { formInline } = options.props;
      console.log("options", formInline);
      const data = Object.assign({}, formInline);
      if (data.notes == "其它") {
        if (!data.remark2) {
          ElMessage.error("请输入其它备注");
          return;
        }
        data.notes = data.remark2;
      }
      handleCharge(data)
        .then(() => {
          done();
          loadData();
          ElMessage.success("处理成功");
        })
        .catch(e => {
          done();
          console.log("e", e);
        });
    }
  });
}

const fullscreenLoading = ref(false);

const exportExcel = async () => {
  try {
    const postData = Object.assign({}, params.value);
    postData.pageSize = 5000;
    postData.page = 1;
    const resData = await getChargeList(postData);
    const data = resData.data.items;
    data.map(item => {
      item.smrzStatus = item.smrzStatus === "1" ? "已实名" : "未实名";
    });
    const dataKeys: string[] = [
      "account",
      "name",
      "smrzStatus",
      "number",
      "handleTime"
    ];
    const titleList: string[] = [
      "账号",
      "姓名",
      "实名状态",
      "充值金额",
      "处理时间"
    ];
    const res: string[][] = data.map(item => {
      const arr = [];
      dataKeys.forEach(column => {
        arr.push(item[column]);
      });
      return arr;
    });
    res.unshift(titleList);
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `${formatDate(new Date())} 充值报表.xlsx`);
    ElMessage.success(`导出成功${data.length}条`);
  } catch (error) {
    console.log(error, "exportError");
  }
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>充值列表</h3>
        </template>
        <template v-if="power.exportExcel" #extra>
          <el-popconfirm
            title="是否确认导出(默认导出最大5000条数据)"
            @confirm="exportExcel"
          >
            <template #reference>
              <el-button
                v-loading.fullscreen.lock="fullscreenLoading"
                type="primary"
                size="default"
                class="mb-4!"
              >
                导出Excel
              </el-button>
            </template>
          </el-popconfirm>
        </template>
        <PlusSearch
          class="mt-5"
          :hasUnfold="false"
          :columns="searchColumns"
          @reset="handleReset"
          @change="handleChange"
          @search="handleSearch"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #status="{ row }">
        <view class="flex flex-col">
          <view>
            <el-tag v-if="row.status == '1'" type="success">成功</el-tag>
            <el-tag v-else-if="row.status == '2'" type="danger">失败</el-tag>
            <el-tag v-else type="primary">待处理</el-tag>
          </view>
          <view v-if="row.posType === 6" class="mt-2">
            在线充值:
            <el-tag v-if="row.orderStatus == 'TRADE_SUCCESS'" type="success"
              >已支付</el-tag
            >
            <el-tag v-else-if="row.orderStatus == 'TRADE_CLOSE'" type="danger"
              >支付失败</el-tag
            >
            <el-tag v-else-if="row.orderStatus == 'TRADE_WAIT'" type="primary"
              >未支付</el-tag
            >
            <el-tag v-else-if="row.orderStatus == 'TRADE_REFUND'" type="warning"
              >已退款</el-tag
            >

            <el-tag v-else type="info">未知</el-tag>
          </view>
        </view>
      </template>
      <template #voucherimage="{ row, index }">
        <el-image
          v-if="row.voucherimage && row.voucherimage.length > 0"
          preview-teleported
          loading="lazy"
          :src="row.voucherimage"
          :preview-src-list="dataList.map(v => v.voucherimage)"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
      <template v-if="power.handle" #operation="{ row }">
        <el-button
          v-if="row.status == '0'"
          link
          type="primary"
          size="small"
          @click="doClick(row)"
        >
          处理
        </el-button>
        <el-tag v-else type="success">已处理</el-tag>
      </template>
    </pure-table>
  </ElCard>
</template>

<style scoped></style>
